<template>
  <!--外形数据表-->

  <div class="table-wrapper w-100">
    <div class="title rounded shadow-harsh pv-10">
      营养成分描述表
      <div class="search">

        <el-popover
          placement="bottom"
          trigger="click">

          <div class="flex-row">
            <el-button size="mini" type="success" @click="handleAdd()">新增</el-button>
            <loader tableName="nutrition_contain" apiName="nutritionContain"></loader>
            <exporter tableName="nutrition_contain"></exporter>

          </div>
          <i slot="reference" class="el-icon-more mr-10"></i>
        </el-popover>


        <el-input
          v-model="search"
          size="mini"
          placeholder="输入名称关键字搜索" />
      </div>

    </div>
    <div class="mt-30">

      <!--    通过字段进行 filter-->
      <el-table
        :v-loading="loading"
        height="450px"
        class="w-100 rounded shadow-harsh p-5"
        :data="tableData.filter(data => !search || data.sourcename.toLowerCase().includes(search.toLowerCase())).slice((currentPage-1)*10,currentPage*10)">

        <el-table-column
          type="index"
          width="50">
        </el-table-column>

        <el-table-column
          label="名称"
          prop="sourcename"
          width="100px"
          align="center">
          <template scope="scope">
            <el-input v-if="scope.$index === editIndex" size="small"
                      v-model="scope.row.sourcename" placeholder="请输入内容">
            </el-input>
            <span v-else>{{scope.row.sourcename}}</span>
          </template>

        </el-table-column>

        <el-table-column
          label="蛋白质"
          prop="protein">
          <template scope="scope">
            <el-input v-if="scope.$index === editIndex" size="small"
                      v-model="scope.row.protein" placeholder="请输入内容">
            </el-input>
            <span v-else>{{scope.row.protein}}</span>
          </template>
        </el-table-column>

        <el-table-column
          label="脂肪"
          prop="fat">
          <template scope="scope">
            <el-input v-if="scope.$index === editIndex" size="small"
                      v-model="scope.row.fat" placeholder="请输入内容">
            </el-input>
            <span v-else>{{scope.row.fat}}</span>
          </template>
        </el-table-column>

        <el-table-column
          label="碳水化合物"
          prop="carbohydrate">
          <template scope="scope">
            <el-input v-if="scope.$index === editIndex" size="small"
                      v-model="scope.row.carbohydrate" placeholder="请输入内容">
            </el-input>
            <span v-else>{{scope.row.carbohydrate}}</span>
          </template>
        </el-table-column>

        <el-table-column
          label="能量（kj/100g）"
          prop="energy">
          <template scope="scope">
            <el-input v-if="scope.$index === editIndex" size="small"
                      v-model="scope.row.energy" placeholder="请输入内容">
            </el-input>
            <span v-else>{{scope.row.energy}}</span>
          </template>
        </el-table-column>

        <el-table-column
          label="钠"
          prop="natrium">
          <template scope="scope">
            <el-input v-if="scope.$index === editIndex" size="small"
                      v-model="scope.row.natrium" placeholder="请输入内容">
            </el-input>
            <span v-else>{{scope.row.natrium}}</span>
          </template>
        </el-table-column>

        <el-table-column
          label="数据源"
          prop="datasource">
          <template scope="scope">
            <el-input v-if="scope.$index === editIndex" size="small"
                      v-model="scope.row.datasource" placeholder="请输入内容">
            </el-input>
            <span v-else>{{scope.row.datasource}}</span>
          </template>
        </el-table-column>

        <el-table-column
          label="负责人"
          prop="principal">
          <template scope="scope">
            <el-input v-if="scope.$index === editIndex" size="small"
                      v-model="scope.row.principal" placeholder="请输入内容">
            </el-input>
            <span v-else>{{scope.row.principal}}</span>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          label="维护时间"
          width="100px"
          sortable
          prop="maintainTime">
          <template scope="scope">
            <el-date-picker
              style="width: 80%"
              v-if="scope.$index === editIndex"
              v-model="scope.row.maintainTime"
              type="date"
              size="small"
              value-format="yyyy-MM-dd"
              placeholder="选择日期">
            </el-date-picker>
            <span v-else>{{scope.row.maintainTime}}</span>
          </template>



        </el-table-column>
<!--        <el-table-column-->
<!--          align="center"-->
<!--          label="维护人"-->
<!--          width="100px"-->
<!--          sortable-->
<!--          prop="maintainer">-->
<!--        </el-table-column>-->
        <el-table-column
          align="center"
          label="插入时间"
          width="100px"
          sortable
          prop="createTime">
        </el-table-column>

        <el-table-column
          align="right">

          <template slot-scope="scope">
            <span v-if="scope.$index !== editIndex">
              <el-button
                size="mini"
                type="warning"
                @click="editIndex = scope.$index; imageUrl = ''">修改
              </el-button>

              <el-popconfirm
                @confirm="handleDelete(scope.$index, scope.row)"
                title="您确定要删除数据吗?">
                <el-button
                  slot="reference"
                  size="mini"
                  type="danger">删除
                </el-button>
              </el-popconfirm>

            </span>
            <span v-else>
            <el-button
              size="mini"
              type="success"
              @click="saveEdit(scope.$index, scope.row)">保存
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleCancel">取消
            </el-button>
            </span>



          </template>
        </el-table-column>
      </el-table>

      <el-pagination class="pagination"
                     @current-change="handleCurrentChange"
                     :current-page="currentPage"
                     :page-size="10"
                     :total="tableData.length"
                     layout="total, prev, pager, next, jumper">
      </el-pagination>



    </div>
  </div>
</template>

<script>
import loader from "./loader";
import exporter from "./exporter";

export default {
  name: "nutrition-table",
  components: {
    loader,
    exporter
  },

  mounted() {
    this.$api.getNutrition().then(res => {
      console.log('getNutrition', res)
      this.tableData = res.data['records'].sort((a, b) => {
        return a.sourcename - b.sourcename
      })
      this.loading = false
    })
  },
  methods: {
    getTableIndexByIndex(index) {
      // 通过表的row index来获取表格数据中的row index 在 list 中使用要 -1
      return index + (this.currentPage - 1) * 10 + 1
    },

    handleDelete(index, row) {
      console.log(index, row);
      this.$api.editNutrition('remove', row.id, row).then(res => {
        console.log(res)
        if (res['success']) {
          let n = this.getTableIndexByIndex(index)
          console.log(n, this.tableData[n-1])
          this.tableData.splice(n-1, 1)

          this.$message({
            message: '删除成功',
            type: 'success',
            duration: 2000
          });
        }
      })
    },
    handleCurrentChange: function(currentPage) {
      this.currentPage = currentPage;
    },

    saveEdit(index, row) {

      let method = row.id ? 'update' : 'save'

      let o = {
        "carbohydrate": row.carbohydrate,
        "createTime": "",
        "energy": row.energy,
        "datasource": row.datasource,
        "fat": row.fat,
        "id": row.id ? row.id : '0',
        "maintainTime": row.maintainTime + " 00:00:00",
        "natrium": row.natrium,
        "principal": row.principal,
        "protein": row.protein,
        "sourcename": row.sourcename,
        "updateTime": ""
      }

      console.log('保存', row.id, row.id ? row.id : 0, o)
      this.$api.editNutrition(method, row.id ? row.id : 0, o).then(res => {
        console.log(res)
        this.$message({
          message: '保存成功',
          type: 'success',
          duration: 2000
        });

        this.$set(this.tableData, this.getTableIndexByIndex(index)-1, res.data.data)
        // this.tableData[this.getTableIndexByIndex(index)-1] = res.data['shapeDesc']
        this.editIndex = null
      })

    },
    handleCancel: function() {
      this.editIndex = null
      this.tableData = this.tableData.filter(ele => {
        return ele.sourcename !== '*'
      })
    },
    handleAdd: function() {
      /*
      * 新增列按照 name * 来识别
      * */

      // 去除之前操作的痕迹
      this.imageUrl = ''
      this.tableData = this.tableData.filter(ele => {
        return ele.sourcename !== '*'
      })

      let nums = this.tableData.push({'sourcename': '*'})
      this.currentPage = Math.floor((nums-1) / 10) + 1
      this.editIndex = nums % 10 === 0 ? 9 : nums % 10 - 1
    }
  },

  data() {
    return {
      tableData: [],
      search: "",
      currentPage: 1,
      loading: true,
      editIndex: null,

      imageUrl: '',
    };
  },
};
</script>

<style scoped>



.avatar-uploader .el-upload {
  border: 1px dashed #616161;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 10px;
  color: #8c939d;
  width: 40px;
  height: 40px;
  line-height: 40px;
  text-align: center;
}
.avatar {
  width: 40px;
  height: 40px;
}
</style>